<script setup>
  import { ref, watch } from 'vue'
  import { Panel, VueFlow, useVueFlow } from '@vue-flow/core'
  const isHidden = ref(false)

  const initialNodes = ref([
    {
      id: '1',
      position: { x: 50, y: 50 },
      data: { label: 'Node 1' },
    },
    {
      id: '2',
      position: { x: 150, y: 150 },
      data: { label: 'Node 2' },
    },
    {
      id: '3',
      position: { x: 300, y: 150 },
      type: 'input',
      sourcePosition: 'right',
      data: { label: 'Node 3' },
    },
    {
      id: '4',
      type: 'output',
      targetPosition: 'left',
      position: { x: 300, y: 400 },
      data: { label: 'Node 4' },
      hidden: Math.random() > 0.5,
    },
  ])
  const initialEdges = ref([
    { id: 'e1-2', source: '1', target: '2', animated: true },
    { id: 'e1-3', source: '3', target: '4', animated: false },
  ])

  watch(isHidden, () => {
    initialNodes.value = initialNodes.value.map((node) => ({ ...node, hidden: isHidden.value }))
    initialEdges.value = initialEdges.value.map((edge) => ({ ...edge, hidden: isHidden.value }))
  })
  const {
    addNodes,
    removeNodes,
    updateNode,
    updateNodeData,
    onNodeDragStart,
    onNodeDrag,
    onNodeDragStop,
    onNodeClick,
    onNodeDoubleClick,
    onNodeContextMenu,
    onNodeMouseEnter,
    onNodeMouseLeave,
    onNodeMouseMove,
    onConnect,
    addEdges,
  } = useVueFlow()

  onConnect(addEdges)

  function generateRandomNode() {
    return {
      id: Math.random().toString(),
      position: { x: Math.random() * 500, y: Math.random() * 500 },
      label: 'Random Node',
    }
  }

  function onAddNode() {
    // add a single node to the graph
    addNodes(generateRandomNode())
  }

  function onAddNodes() {
    // add multiple nodes to the graph
    addNodes(Array.from({ length: 10 }, generateRandomNode))
  }
  function removeMultipleNodes() {
    removeNodes(['1', '2'])
  }

  onNodeDoubleClick((event) => {
    console.log('Node dragged', event)
  })

  onNodeContextMenu((event) => {
    console.log('Node drag stopped', event)
  })
  function onUpdateNode() {
    console.log(123)
    updateNode('2', { selectable: false, draggable: false })
    updateNodeData('e1-2', { hello: 'mona' })

    setTimeout(() => {
      console.log('initialEdges_____', initialEdges)
    }, 1000)
  }
</script>

<template>
  <div class="w-full h-full">
    <VueFlow :nodes="initialNodes" :edges="initialEdges">
      <Panel>
        <button type="button" @click="onAddNode">Add a node</button> |
        <button type="button" @click="onAddNodes">Add multiple nodes</button> |

        <button type="button" @click="removeMultipleNodes">Remove Node 1 and 2</button> |

        <button type="button" @click="onUpdateNode">Update EL 2</button> |

        <button type="button" @click="isHidden = !isHidden">显示隐藏</button> |
      </Panel>
    </VueFlow>
  </div>
</template>
